package com.yyl.dome.bus.controller.WordBatch;

import ch.qos.logback.core.util.FileUtil;
import cn.hutool.core.date.DateTime;
import com.yyl.dome.bus.utils.CustomXWPFDocument;
import com.yyl.dome.bus.utils.WordUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import ch.qos.logback.core.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.web.servlet.ModelAndView;
import java.net.URLEncoder;

@Api(tags = "WordFlow word批量文件")
@RequestMapping("/WordFlow")
@RestController
public class FlowContriller {

    @RequestMapping("/test/toWord")
    public ModelAndView toWord(HttpServletRequest request, HttpServletResponse response) throws IOException {

        File file = createDoc();

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode("测试的，统计-导出时间"+ new DateTime() +".doc", "utf-8"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

    private File createDoc(){
        // 创建数据
        Map<String,Object> dataMap = new HashMap<String, Object>();

        dataMap.put("cwlx", "测试的");
        List<?> eList = new ArrayList<>();// 这里是获取list列表的方法
        dataMap.put("czsj",new DateTime());// 这里是获取当前时间的一种方式，可以根据自己程序自行修改  DateTimeUtils.getDateTime("yyyyMMddHHmmss")
        dataMap.put("eList", eList);

        // 获取模板
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/tpl");
        Template t = null;

        String name = "temp"+(int)(Math.random()*1000)+".doc";
        File file = new File(name);
        try {
            t = configuration.getTemplate("model.xml");
            t.setEncoding("UTF-8");

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成压缩包
    public static void writeZip(List<String> files, String zipname) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String fileName = zipname + ".zip";
        OutputStream os = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        ZipOutputStream zos = new ZipOutputStream(os);
        byte[] buf = new byte[8192];
        int len;
        for (int i = 0; i < files.size(); i++) {
            File file = new File(files.get(i));
            if (!file.isFile()) continue;
            ZipEntry ze = new ZipEntry(file.getName());
            zos.putNextEntry(ze);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            while ((len = bis.read(buf)) > 0) {
                zos.write(buf, 0, len);
            }
            bis.close();
            zos.closeEntry();
        }
        zos.closeEntry();
        zos.close();
        // 删除下载的文件
        for (int i = 0; i < files.size(); i++) {
            File file = new File(files.get(i));
            if (!file.isFile()) continue;
            file.delete();
        }

    }
    @RequestMapping(value = "/export")
    @ApiOperation("测试用例Word压缩包")
    public void export(HttpServletRequest request,HttpServletResponse response) throws Exception{
        WordUtil xwpfTUtil = null;
        OutputStream os = null;
        InputStream is = null;
        List<String> files = new ArrayList();
        for (int i = 0; i < 2; i++) {
            xwpfTUtil = new WordUtil();
            Map<String, Object> params = new HashMap<>();
            params.put("${Name}", "Fisher3652");
            params.put("${Sex}", "男");
            params.put("${Desc}", "18岁\tJAVA开发\r熟悉JVM基本原理");
//            params.put("${@Pic}", "C:\\Users\\111\\Pictures\\123.jpg");
            CustomXWPFDocument doc;
            is = FileUtil.class.getClassLoader().getResourceAsStream("static/Demo.docx");
            doc = new CustomXWPFDocument(is);
            xwpfTUtil.replaceInPara(doc, params);
            xwpfTUtil.replaceInTable(doc, params);
            String path = request.getSession().getServletContext().getContextPath() + "/word";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = request.getSession().getServletContext().getContextPath() + "/word/" + i + ".docx";
            os = new FileOutputStream(new File(fileName));
            files.add(fileName);
            doc.write(os);
            System.out.println("word成功生成");
        }
        xwpfTUtil.close(os);
        xwpfTUtil.close(is);
        os.flush();
        os.close();
        writeZipTWO(files, "文件汇总");

    }
// 压缩文件
    private void writeZipTWO(List<String> files, String zipname) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String fileName = zipname + ".zip";
        OutputStream os = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        ZipOutputStream zos = new ZipOutputStream(os);
        byte[] buf = new byte[8192];
        int len;
        for (int i = 0; i < files.size(); i++) {
            File file = new File(files.get(i));
            if (!file.isFile()) continue;
            ZipEntry ze = new ZipEntry(file.getName());
            zos.putNextEntry(ze);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            while ((len = bis.read(buf)) > 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
        }
        zos.closeEntry();
        zos.close();
    }



}
